package com.sbl.bajw.pc.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.fileupload.FileItem;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sbl.bajw.common.MyBatisDao;
import com.sbl.bajw.common.web.MessageException;
import com.sbl.bajw.common.web.RequestUnit;
import com.sbl.bajw.common.web.SessionUnit;
import com.sbl.bajw.mapper.AttFileDao;
import com.sbl.bajw.mapper.OperationLogModelDao;
import com.sbl.bajw.mapper.PrizeAlarmModelDao;
import com.sbl.bajw.pc.model.AttFileModel;
import com.sbl.bajw.pc.model.OperationLogModel;
import com.sbl.bajw.pc.model.PrizeAlarmModel;
import com.sbl.bajw.util.AmrToMp3Util;
import com.sbl.bajw.util.LogUtil;

@Service
public class PrizeAlarmModelService {

	@Resource
	private PrizeAlarmModelDao dao;
	
	@Resource
	private MyBatisDao gridDao;

	@Resource
	private OperationLogModelDao op_dao;
	
	@Resource
	private AttFileService attfileService;
	
	@Resource
	private AttFileDao attfileDao;
	
	static Logger log;
	
	static{
		log = LogUtil.getLogger("PrizeAlarm");
	}
	
	@Transactional(readOnly = false)
	public void insert(PrizeAlarmModel model) throws Exception{
		try {
			log.info(model.getCreateBy() + "图片入库");
			uploadFile(model);
			log.info(model.getCreateBy() + "图片入库成功，属性入库");
			dao.insert(model);
			log.info(model.getCreateBy() + "属性入库成功");
		} catch (Exception e) {
			log.info(model.getCreateBy() + "文件上传异常：" + e.getMessage());
			e.printStackTrace();
			throw e;
		}
		
		//有奖报警信息入库操作日志
		OperationLogModel entity = new OperationLogModel();
		entity.setOperationuserid(model.getCreateBy());
		entity.setOperationcontent("有奖报警信息入库");
		entity.setOperationname("有奖报警信息入库");
		entity.setActionid("1");
		op_dao.insert(entity);
		
	}
	
	public HashMap<String, Object> getModel(String id){
		HashMap<String, Object> model = dao.getModel(id);
		return model;
	}
	
	public List<HashMap<String, Object>> getAttfileByPrizeAlarmId(String id){
		List<HashMap<String, Object>> list = dao.getAttfileByPrizeAlarmId(id);
		return list;
	}
	
	public HashMap<String, Object> getAttfileMp3(List<HashMap<String, Object>> list){
		List<HashMap<String, Object>> voice = new ArrayList<HashMap<String,Object>>();
		HashMap<String, Object> map = new HashMap<String, Object>();
		for(int i = 0; i < list.size(); i++){
			if("record".equals(list.get(i).get("FILETYPE"))){
				voice.add(list.get(i));
			}
		}
		if(voice.size() > 1){
			for(int i = 0; i < voice.size(); i++){
				String str = voice.get(i).get("SMALLIMGURL").toString().split("\\.")[1];
				if("mp3".equals(str)){
					map.put("FILEPATH", voice.get(i).get("SMALLIMGURL"));
					map.put("FILETYPE", voice.get(i).get("FILETYPE"));
				}
			}
		}else if(voice.size() == 1){
			String oldFilePath = voice.get(0).get("SMALLIMGURL").toString();
			String[] arr = oldFilePath.split("\\.");
			String newFilePath = arr[0] + ".mp3";
			AmrToMp3Util.AmrToMp3(oldFilePath, newFilePath);
			String path = newFilePath;
			String[] str = path.split("/");
			String filename = str[str.length - 1];
			String[] data = filename.split("\\.")[0].split("_");
			String id = data[data.length - 1];
			AttFileModel filemodel = new AttFileModel();
			filemodel.setBusinessType("2");
			filemodel.setGroupid(id);
			filemodel.setUserid(SessionUnit.getUserId());
			filemodel.setFiletype("record");
			filemodel.setSmallimgurl(path);
			attfileDao.insert(filemodel);;
			map.put("FILEPATH", newFilePath);
			map.put("FILETYPE", voice.get(0).get("FILETYPE"));
		}
		return map;
	}
	
	public List<HashMap<String, Object>> getListApp(HashMap<String, Object> parm){
		List<HashMap<String, Object>> list = dao.getListApp(parm);
		return list;
	}
	
	public int getCountApp(HashMap<String, Object> parm){
		int num = dao.getCountApp(parm);
		return num;
	}
	
	public PrizeAlarmModel detailApp(HashMap<String, String> parm){
		PrizeAlarmModel model = dao.detailApp(parm);
		return model;
	}
	
	public String getPrizeAlarmList(HashMap<String, Object> parm){
		String json = gridDao.selectPage(PrizeAlarmModelDao.class, parm, "getPrizeAlarmList");
		
		//有奖报警列表查询操作日志
		OperationLogModel entity = new OperationLogModel();
		entity.setOperationuserid(SessionUnit.getUserId());
		entity.setOperationcontent("有奖报警列表查询");
		entity.setOperationname("有奖报警列表查询");
		entity.setActionid("4");
		op_dao.insert(entity);
		
		return json;
	}
	
	public List<HashMap<String, Object>> downloadPrizeAlarmList(HashMap<String, Object> parm){
		List<HashMap<String, Object>> list = dao.getPrizeAlarmList(parm);
		
		//有奖报警列表查询操作日志
		OperationLogModel entity = new OperationLogModel();
		entity.setOperationuserid(SessionUnit.getUserId());
		entity.setOperationcontent("有奖报警列表查询");
		entity.setOperationname("有奖报警列表查询");
		entity.setActionid("4");
		op_dao.insert(entity);
		
		return list;
	}
	
	public String uploadFile(PrizeAlarmModel model) throws Exception {
		String id = dao.getPrizeAlarmId();

		if (id == null || id.equals("")) {
			throw new MessageException("ID不能为空", "2");
		}
		
		String resultPath = "";
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmssS");
		FileItem item = null;
		int i = 1;
		
		if((item = RequestUnit.getFileItem("img" + i)) == null){
			throw new MessageException("图片不能为空", "3");
		}
		
		while((item = RequestUnit.getFileItem("img" + i)) != null){
			String dataStr = sf.format(Calendar.getInstance().getTime());
			
			AttFileModel filemodel = new AttFileModel();
			filemodel.setBusinessType("2");
			filemodel.setFileDir("alarm/image");
			filemodel.setFileName(dataStr + i +  "_img_" + id);
			filemodel.setGroupid(id);
			filemodel.setItem(item);
			filemodel.setUserid(model.getCreateBy());
			filemodel.setFiletype("img");
			attfileService.insert(filemodel);
			log.info(model.getCreateBy() + "图片上传成功：" + resultPath);
			i++;
		}

		model.setPicfileids(id);
		
		FileItem record = RequestUnit.getFileItem("voice");
		if (record != null) {
			String dataStr = sf.format(Calendar.getInstance().getTime());
			
			AttFileModel filemodel = new AttFileModel();
			filemodel.setBusinessType("2");
			filemodel.setFileDir("alarm/voice");
			filemodel.setFileName(dataStr + "_record_" + id);
			filemodel.setGroupid(id);
			filemodel.setItem(record);
			filemodel.setUserid(model.getCreateBy());
			filemodel.setFiletype("record");
			attfileService.insert(filemodel);
			model.setRecordid(id);
			log.info(model.getCreateBy() + "录音上传成功:" + resultPath);
		} else {
			log.info(SessionUnit.getSessionId() + "没有录音数据");
		}
		
		return resultPath;
	}
}
